﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using serviceMaker.RssService;
using System.Collections.Generic;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Command;
      
namespace ViewModel.Rss
{
    public class DataItemRead : DataItem
    {
        public DataItemRead(DataItem parent)
        {
            this.date = parent.date;
            this.description = parent.description;
            this.fk_id_Rss = parent.fk_id_Rss;
            this.guid = parent.guid ;
            this.id = parent.id;
            this.image = parent.image;
            this.isRead = parent.isRead;
            this.link = parent.link;
            this.media = parent.media;
            this.titre = parent.titre;
            colorRead = new SolidColorBrush();
            Color tmp = new Color();
            if (this.isRead == true)
            {

                tmp.R = tmp.G = tmp.B = 180;
                tmp.A = 255;
              
            }
            else
            {
                tmp = (Color)Application.Current.Resources["PhoneAccentColor"];
            }
            string tmpUri = image.Contains(",") == true ? image.Split(new char[] { ',' })[0] : image;
            ImageUri = new Uri(tmpUri == null || tmpUri == "" ? "http://192.168.0.7:8080/ServeurRSS_1_0/no_photo.jpg" : tmpUri);
            colorRead.Color = tmp;
        }

        private Uri imageUri;
        public Uri ImageUri
        {
            get { return imageUri; }
            set
            {
                if (value != imageUri)
                {
                    imageUri = value;
                    RaisePropertyChanged("ImageUri");
                }
            }
        }
		
        private SolidColorBrush colorRead;
        public SolidColorBrush ColorRead
        {
            get { return colorRead; }
            set
            {
                if (value != colorRead)
                {
                    colorRead = value;
                    RaisePropertyChanged("ColorRead");
                }
            }
        }
    }

    //public class RssTreeObservable
    //{ 
    //    RssTreeObservable(RssTree tree)
    //    {
    //        ConstructLevel(tree, this);
    //    }

    //   public RssTreeObservable ConstructLevel(RssTree tree, RssTreeObservable newTree)
    //    {
    //        tre
    //    }

    //}

    public class RssViewModel : InfoViewModelBase
    {
        static int count = 0;
        #region constructeur/destructeur
        public RssViewModel()
        {
            RssService = new ServiceRssManagementClient();
            listRss = null;
            RssSelected = null;
            ReloadData = new RelayCommand(ExecuteReload, CanExecuteReload);
            Messenger.Default.Register<string>(this, "reload", (str) => {
                if (this.CanExecuteReload())
                    this.ExecuteReload();
            });
     
        }

        #endregion 

        #region ServiceRssClient

        private ServiceRssManagementClient rssService;
        public ServiceRssManagementClient RssService
        { get; set; }
        
        #endregion

        #region ListRss
        private ObservableCollection<DataRss> listRss;
        public ObservableCollection<DataRss> ListRss
        {
            get 
            {
                if (listRss == null)
                    askForListRss(false);
              return listRss;
                
            }
            private set
            {
                if (value != listRss)
                {
                    listRss = value;
                    RaisePropertyChanged("ListRss");
                }
            }
        }


  

        public void askForListRss(bool? owner)
        { 
            if (clientInfos.Authenticate == true) {
                RssService.CookieContainer = clientInfos.cc;
                RssService.getAllRssForUserCompleted += new EventHandler<getAllRssForUserCompletedEventArgs>(RssService_getAllRssForUserCompleted);
                RssService.getAllRssForUserAsync(new getAllRssForUserRequest(clientInfos.CurrentUser.id, owner));
            }
        }

        public void RssService_getAllRssForUserCompleted(object sender, getAllRssForUserCompletedEventArgs arg)
        {
            if (arg != null && arg.Error == null)
            {
                ListRss = new ObservableCollection<DataRss>(arg.Result.getAllRssForUserResult);
                foreach (DataRss tmp in ListRss)
                    if (tmp.image == "")
                        tmp.image = "http://192.168.0.7:8080/ServeurRSS_1_0/no_photo.jpg";
               
            }
        }


           private DataRss rssSelected;
        public DataRss RssSelected
        {
            get { return rssSelected; }
            set
            {
                if (value != rssSelected)
                {
                    rssSelected = value;
                    RaisePropertyChanged("ItemSelected");
                }
            }
        }

        #endregion
        #region listItemRss

        private DataItemRead itemSelected;
        public DataItemRead ItemSelected
        {
            get { return itemSelected; }
            set
            {
                if (value != itemSelected)
                {
                    Color tmp = new Color();
                    tmp.R = tmp.G = tmp.B = 180;
                    tmp.A = 255;
                    itemSelected = value;
                    if (itemSelected != null)
                    {
                        itemSelected.isRead = true;
                        itemSelected.ColorRead.Color = tmp;
                        RaisePropertyChanged("ListItemRss");
                    }
                    RaisePropertyChanged("ItemSelected");
                }
            }
        }

        private ObservableCollection<DataItemRead> listItemRss;
        public ObservableCollection<DataItemRead> ListItemRss
        {
            get
            {
                if (listItemRss == null
                    || (listItemRss.Count > 0 && RssSelected != null && listItemRss[0].fk_id_Rss != RssSelected.id))
                    askForListItemRss(false);
               // TODO envoi un message à la vue pour specifier qu'il n'y a rien à afficher
                return listItemRss;

            }
            private set
            {
                if (value != listItemRss)
                {
                    listItemRss = value;
                    RaisePropertyChanged("ListItemRss");
                }
            }



        }

        public ICommand SetReadedItem
        { get; set; }

        public void ExecuteSetReaded()
        { 
            if (listItemRss == null)
                return;
            List<Guid> param = new List<Guid>();
            foreach (DataItemRead item in listItemRss)
                if (item.isRead == true)
                param.Add(item.id);

            RssService.CookieContainer = clientInfos.cc;
            RssService.setReadedItemAsync(new setReadedItemRequest(param, clientInfos.CurrentUser.id));

        }


        public bool CanExecuteSetReaded()
        {
            return true;
        }

        public void askForListItemRss(bool? owner)
        {
            if (clientInfos.Authenticate == true)
            {
                RssService.CookieContainer = clientInfos.cc;
                RssService.getListItemForRssCompleted += new EventHandler<getListItemForRssCompletedEventArgs>(
                    (sender, arg) =>
                    {
                        if (arg != null && arg.Error == null)
                        {
                            ListItemRss = new ObservableCollection<DataItemRead>();
                            List<DataItem> tmpList = arg.Result.getListItemForRssResult != null ? arg.Result.getListItemForRssResult : new List<DataItem>();
                            foreach (DataItem tmp in tmpList)
                            {
                                if (tmp.image == "")
                                    tmp.image = "http://192.168.0.7:8080/ServeurRSS_1_0/no_photo.jpg";
                                ListItemRss.Add(new DataItemRead(tmp));
                            }
                           RaisePropertyChanged("ListItemRss");
                            if (tmpList.Count <= 0)
                                NoData = "Aucune Données disponible pour le moment, essayé de recharger la page";
                            else
                                NoData = "";
                        }
                    });
                if (RssSelected != null)
                    RssService.getListItemForRssAsync(new getListItemForRssRequest(RssSelected.id, 20, 0));
                else
                    throw (new NullReferenceException("ItemSelected est Null"));
            }
        }


        private string noData;
        public string NoData
        {
            get
            {
                return noData;
            }
            set
            {
                if (value != noData)
                {
                    noData = value;
                    RaisePropertyChanged("NoData");
                }
            }
        }

        #endregion

        public    ICommand ReloadData
        {get; set;}

        public void ExecuteReload()
        {
            if (RssSelected != null)
                askForListItemRss(false);
            else
                askForListRss(false);

        }

        public bool CanExecuteReload()
        {
            return true;
        }

        #region HierarchicalListRss

        //private RssTreeObservable userTreeBind;
        //public RssTreeObservable UserTreeBind
        //{ 
        //    get { return userTreeBind; }
        //    set 
        //    {
        //        if (value != userTreeBind)
        //        {
        //            userTreeBind = value;
        //            RaisePropertyChanged("UserTreeBind");
        //        }
        //    }
        //}

        #endregion
    }
}
